# -*- coding: utf-8 -*-
"""Main Controller"""
try:
    from mx import DateTime as mxdt
except ImportError:
    print "You need to install python-egenix-mx-base"

import re
from tg import expose, flash, require, url, request, redirect,tmpl_context,validate, config
from pylons.i18n import ugettext as _, lazy_ugettext as l_
#from catwalk.tg2 import Catwalk
from repoze.what import predicates
from formencode import validators,Schema
from lifepyscle.lib.base import BaseController
from lifepyscle.lib.uploader import *
from lifepyscle.model import DBSession, metadata
from lifepyscle.controllers.error import ErrorController
from lifepyscle import model
from lifepyscle.model import *
from lifepyscle.controllers.secure import SecureController
from lifepyscle.widgets import event
from lifepyscle.widgets import reminder
from lifepyscle.widgets.fancybox import FancyBox
from lifepyscle.widgets.dummy import dummy_dynamicform
import os,shutil,pylons
from common import frequencies, MAX_RECUR,choice_recur_count
cat="event" # added to every returned dict
event_form = event.event_form
reminder_form = reminder.reminder_form
reggie = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",re.IGNORECASE)

from lifepyscle.widgets.event import EventSchema

def mail_ok(raw_mail):
    a = re.match(reggie,raw_mail)
    try:
        x = a.group()
    except AttributeError:
        return False
    else:
        return True

class EventController(BaseController):
    @expose('lifepyscle.templates.test_autoc')
    def index(self, **kw):
        tmpl_context.add_event_form = add_event.add_event_form
        tmpl_context.dummy_dynamicform = dummy_dynamicform
        form_id = "add_event_form"
        fieldset_id = "add_event_form_AddEventFieldSet" # nasty hack to get the tw generated fieldset id
        return dict(page="Add Event",cat=cat,form_id=form_id,fieldset_id=fieldset_id)

    @expose('json')
    def fetch_types(self):
        types = DBSession.query(EventType.type).all()
        return dict(data=types)

    @expose('lifepyscle.templates.test_event')
    def test(self,**kw):
        print kw
        tmpl_context.event_form = event_form(child_args={'count':{'options':choice_recur_count},'freq':{'options':frequencies}})
        return dict(r=MAX_RECUR,cat=cat)


    @expose()
    @validate(form=event_form,error_handler=test)
    def add(self,**kw):
        r2r = kw['r2r'] # r2r = redirect to record - go to /record/view/{record_id}#events
        redir_url = '%s'%r2r
        record_id = kw['record_id']
        starts = kw['starts']
        ends = kw['ends']
        ends_str = kw['ends_str']
        desc = kw['desc']
        title = kw['title']
        event_type = kw['event_type']
        print ends_str
        try:
            R = DBSession.query(Record).filter(Record.record_id==record_id).one()
        except:
            flash("No record exists with id %s"%record_id,"error")
            redirect(url(redir_url))
        if len(event_type):
            try:
                ET = DBSession.query(EventType).filter(EventType.type=='%s'%event_type).one()
            except: # import the proper exception for "no record found"
                ET = EventType()
                ET.type = event_type # can't add a description here - user will have to edit later
                DBSession.add(ET)
        # now the event_type is available to the new event as E - irrespective of whether it existed or not
        try:
            E = Event()
            R.events.append(E)
            E.starts = starts
            E.ends = ends
            E.ends_str = ends_str
            E.title = title
            E.description = desc
            E.type = ET
        except Exception,e:
            flash("Could not add the event: %s"%str(e),'error')
        else:
            flash("Successfully added the event","info")

        redirect(url(redir_url))


    @expose('lifepyscle.templates.view_event')
    def view(self,id=None,**kw):
        if not id:
            flash('No event id sent','warning')
            redirect(url('/event/upcoming'))
        else:
            try:
                E = DBSession.query(Event).filter(Event.event_id==id).one()
            except:
                flash('No event exists with that id','error')
                redirect(url('/event/upcoming'))
            else:
                tmpl_context.fb = FancyBox()
                tmpl_context.add_reminder = reminder_form()
                r2r ='/record/view/%d#events'%E.record.record_id
                tmpl_context.event_form = event_form(action="/event/update",value=dict(event_id=E.event_id,r2r=r2r,title=E.title,event_type=E.type.type,desc=E.description,starts=E.starts,ends=E.ends_str,record_id=E.record.record_id))
                return dict(cat=cat,event=E)

    @expose()
    def delete(self,id=None,**kw):
        try:
            E = DBSession.query(Event).filter(Event.event_id==id).one()
        except:
            flash("No event exists with that id","error")
            redirect(url('/event/upcoming'))
        else:
            R = E.record
            return_url = url('/record/view/%d#events'%R.record_id)
            try:
                DBSession.delete(E)
            except Exception,e:
                flash(str(e),"error")
            else:
                flash("Event with id %s successfully deleted"%id,"info")
                redirect(return_url)

    @expose()
    @validate(form=event_form)
    def update(self,**kw):
        r2r = kw['r2r'] # r2r = redirect to record - go to /record/view/{record_id}#events
        redir_url = '%s'%r2r
        record_id = kw['record_id']
        starts = kw['starts']
        ends = kw['ends']
        ends_str = kw['ends_str']
        desc = kw['desc']
        title = kw['title']
        event_type = kw['event_type']
        event_id = kw['event_id']
        try:
            E = DBSession.query(Event).filter(Event.event_id==event_id).one()
        except:
            flash("No event exists with id %s"%event_id,"error")
            redirect(url(redir_url))
        if len(event_type):
            try:
                ET = DBSession.query(EventType).filter(EventType.type=='%s'%event_type).one()
            except: # import the proper exception for "no record found"
                ET = EventType()
                ET.type = event_type # can't add a description here - user will have to edit later
                DBSession.add(ET)
        # now the event_type is available to the new event as E - irrespective of whether it existed or not
        try:
            E.starts = starts
            E.ends = ends
            E.ends_str = ends_str
            E.title = title
            E.description = desc
            E.type = ET
        except Exception,e:
            flash("Could not update the event: %s"%str(e),'error')
        else:
            flash("Successfully updated the event","info")

        redirect(url(redir_url))

    @expose('json')
    def markAchieved(self,event_id=None,**kw):
        if not event_id:
            return dict(mark_status=1,mark_msg='No event id provided')
        else:
            try:
                E = DBSession.query(Event).filter(Event.event_id==event_id).one()
            except:
                return dict(mark_status=1,mark_msg='No event exists with id %s'%event_id)
            else:
                E.achieved = True
                return dict(mark_status=0,mark_msg='Event with id %s has been marked as achieved'%event_id)

    @expose('json')
    def markNotAchieved(self,event_id=None,**kw):
        if not event_id:
            return dict(mark_status=1,mark_msg='No event id provided')
        else:
            try:
                E = DBSession.query(Event).filter(Event.event_id==event_id).one()
            except:
                return dict(mark_status=1,mark_msg='No event exists with id %s'%event_id)
            else:
                E.achieved = False
                return dict(mark_status=0,mark_msg='Event with id %s has been marked as not achieved'%event_id)


